/****************
 *@description: 抖音数据看板
 *@author: Xhd
 *@date: 2023-09-08 09:39:32
 *@version: V1.0.0
*************************************************************************/

import React, { Component } from 'react';
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import { apiThirdAdvertStatisticsPage, apiThirdAdvertStatisticsOverview, apiThirdAdvertStatisticsExport } from '@/request/dataBoard';
import TheQueryForm from '@/components/TheQueryForm';
import store from "@/store/store"
import { exportSheetTable } from '@/utils/exportTable.js';
import _ from 'lodash';
import { getDateTime3 } from '@/utils/getDate'
import { Tabs, Tooltip, Row, Col } from 'antd';
import { QuestionCircleOutlined } from '@ant-design/icons';
import "./style/style.less"

const { TabPane } = Tabs;
//流量投放效果
class weChatAD extends Component {
  constructor() {
    super()
    this.formRef_search = React.createRef()
    this.queryFormRef_devote = React.createRef()
    this.queryFormRef_retained = React.createRef()
    this.voucherFormRef = React.createRef()
    this.state = {
      columns_devote: [
        {
          title: "日期",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "广告平台",
          dataIndex: "advertSource",
          key: "advertSource",
          render: (text, render) => {
            let label = "/"
            switch (text) {
              case '0':
                label = "其他"
                break;
              case '3':
                label = "抖音"
                break;
              case '21':
                label = "腾讯"
                break;
              default:
                break;
            }
            return label
          }
        },
        {
          title: "来源",
          dataIndex: "platform",
          key: "platform",
          render: (text, render) => {
            let label = "/"
            switch (text) {
              case "ios":
                label = "iPhone"
                break;
              case "Android":
                label = "Android"
                break;
              case "weChatMini":
                label = "微信小程序"
                break;
              case "h5":
                label = "h5"
                break;
              default:
                break;
            }
            return label
          }
        },
        {
          title: "激活用户",
          dataIndex: "activeCount",
          key: "activeCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  通过广告或自然流量访问的用户
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "累计注册用户",
          dataIndex: "registerCount",
          key: "registerCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当天激活用户中注册的用户数量之和
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "累计付款用户",
          dataIndex: "payCount",
          key: "payCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当天激活用户中付款的用户数量之和
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "用户累计付款金额",
          dataIndex: "registerPayPrice",
          key: "registerPayPrice",
          render: text => <React.$price price={text} />,
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当天激活的用户累计到查询时的实付金额数
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "累计访问次数",
          dataIndex: "visitCount",
          key: "visitCount",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  累计注册用户访问应用的次数
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
      ],
      columns_retained: [
        {
          title: "日期",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "广告平台",
          dataIndex: "advertSource",
          key: "advertSource",
          render: (text, render) => {
            let label = "/"
            switch (text) {
              case '0':
                label = "其他"
                break;
              case '3':
                label = "抖音"
                break;
              case '21':
                label = "腾讯"
                break;
              default:
                break;
            }
            return label
          }
        },
        {
          title: "来源",
          dataIndex: "platform",
          key: "platform",
          render: (text, render) => {
            let label = "/"
            switch (text) {
              case "ios":
                label = "iPhone"
                break;
              case "Android":
                label = "Android"
                break;
              case "weChatMini":
                label = "微信小程序"
                break;
              case "h5":
                label = "h5"
                break;
              default:
                break;
            }
            return label
          }
        },
        {
          title: "当日注册用户",
          dataIndex: "registerTotal",
          key: "registerTotal",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当天注册了用户数量之和
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "次日留存率",
          dataIndex: "nextDayRetention",
          key: "nextDayRetention",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当日注册第二天访问的应用的用户数/当日注册用户*100%
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "7日留存率",
          dataIndex: "sevenDayRetention",
          key: "sevenDayRetention",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当日注册第7天访问的应用的用户数/当日注册用户*100%
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "15日留存率",
          dataIndex: "fifteenDayRetention",
          key: "fifteenDayRetention",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当日注册第15天访问的应用的用户数/当日注册用户*100%
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
        {
          title: "30日留存率",
          dataIndex: "thirtiethDayRetention",
          key: "thirtiethDayRetention",
          filterDropdown: true,
          filterIcon: () => {
            return (
              <Tooltip zIndex={999} placement="top" title={() => {
                return <div>
                  当日注册第30天访问的应用的用户数/当日注册用户*100%
                </div>
              }
              }  >
                <QuestionCircleOutlined />
              </Tooltip>
            );
          },
        },
      ],
      dataSource: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 0,
      form_show: true,
      searchOption: [
        {
          field: "advertSourceList",
          label: "广告平台",
          placeholder: "请选择",
          required: false,
          rules: [],
          type: "Select",
          options: [
            { value: "3", label: "抖音" },
            { value: "21", label: "腾讯" },
            { value: "0", label: "其他" },
          ],
          mode: "multiple",
          defaultValue: []
        },
        {
          field: "platformList",
          label: "来源",
          placeholder: "请选择",
          required: false,
          rules: [],
          type: "Select",
          options: [
            { value: "ios", label: "iPhone" },
            { value: "Android", label: "Android" },
            { value: "weChatMini", label: "微信小程序" },
            { value: "h5", label: "h5" },
          ],
          mode: "multiple",
          defaultValue: []
        },
        { field: 'times', label: '激活时间', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
      ],
      queryForm: {},
      defaultActiveKey: "1",
      overView: ""
    }
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'weChat') {
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.getData()
        this.getOverViewData()
      })
    } else {
      this.getData()
      this.getOverViewData()
    }
  }
  getData(values) {
    let { pageNo, pageSize } = this.state.pageData
    if (values && !_.isEmpty(values.times)) {
      values.beginTime = getDateTime3(values.times[0])
      values.endTime = getDateTime3(values.times[1])
      delete (values.times)
    }
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        pageNo, pageSize, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'weChat',
          ...params
        }
      })
      let res = await apiThirdAdvertStatisticsPage({
        pageNo, pageSize, ...this.state.queryForm,
      })

      if (res.code === 0) {
        this.setState({
          dataSource: res.data,
          total: res.totalCount
        })
      }
    })
  }
  getOverViewData = async (values) => {
    if (values && !_.isEmpty(values.times)) {
      values.beginTime = getDateTime3(values.times[0])
      values.endTime = getDateTime3(values.times[1])
      delete (values.times)
    }
    let res = await apiThirdAdvertStatisticsOverview({ ...values })
    if (res.code === 0) {
      if (res.data) {
        this.setState({
          overView: res.data
        })
      } else {
        this.setState({
          overView: {
            activeCount: 0,
            registerCount: 0,
            payCount: 0,
            registerPayPrice: 0
          }
        })
      }
    }
  }

  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };

  onReset() {
    const { defaultActiveKey } = this.state
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
      if (defaultActiveKey === "1") {
        this.getOverViewData()
      }
    })
  }

  onFormSearch(values) {
    const { defaultActiveKey } = this.state
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
      if (defaultActiveKey === "1") {
        this.getOverViewData(values)
      }
    })
  }

  toExport = async (type) => {
    const { queryForm } = this.state
    // if (Object.keys(queryForm).includes("beginTime") && Object.keys(queryForm).includes("endTime")) {
    await apiThirdAdvertStatisticsExport({ ...queryForm }).then(res => {
      if (res.code === 0 && res.data) {
        let th_arr = []
        let fileName = ''
        if (type === '1') {
          fileName = '投放数据'
          th_arr = [
            {
              title: '投放数据',
              prop: '',
              children: [
                {
                  title: "日期",
                  prop: "createTime",
                },
                {
                  title: "广告平台",
                  prop: "advertSource",
                },
                {
                  title: "来源",
                  prop: "platform",
                },
                {
                  title: "激活用户",
                  prop: "activeCount",
                },
                {
                  title: "累计注册用户",
                  prop: "registerCount",
                },
                {
                  title: "累计付款用户",
                  prop: "payCount",
                },
                {
                  title: "用户累计付款金额",
                  prop: "registerPayPrice",
                },
                {
                  title: "累计访问次数",
                  prop: "visitCount",
                },
              ]
            },
          ]
        } else {
          fileName = '留存效果'
          th_arr = [
            {
              title: '留存效果',
              prop: '',
              children: [
                {
                  title: "日期",
                  prop: "createTime",
                },
                {
                  title: "广告平台",
                  prop: "advertSource",
                },
                {
                  title: "来源",
                  prop: "platform",
                },
                {
                  title: "当日注册用户",
                  prop: "registerTotal",
                },
                {
                  title: "次日留存率",
                  prop: "nextDayRetention",
                },
                {
                  title: "7日留存率",
                  prop: "sevenDayRetention",
                },
                {
                  title: "15日留存率",
                  prop: "fifteenDayRetention",
                },
                {
                  title: "30日留存率",
                  prop: "thirtiethDayRetention",
                },
              ]
            },
          ]
        }

        let tb_arr = []
        res.data.forEach((item, index) => {
          let platform = ""
          let advertSource = ""
          switch (item.advertSource) {
            case '0':
              advertSource = "其他"
              break;
            case '3':
              advertSource = "抖音"
              break;
            case '21':
              advertSource = "腾讯"
              break;
            default:
              break;
          }
          switch (item.platform) {
            case "ios":
              platform = "iPhone"
              break;
            case "Android":
              platform = "Android"
              break;
            case "weChatMini":
              platform = "微信小程序"
              break;
            case "h5":
              platform = "h5"
              break;
            default:
              break;
          }
          tb_arr.push({
            index: index + 1,
            createTime: item.createTime || '/',
            advertSource: advertSource || '/',
            platform: platform || '/',
            activeCount: item.activeCount || "0",
            registerCount: item.registerCount || '0',
            payCount: item.payCount || '0',
            registerPayPrice: (item.registerPayPrice / 100).toFixed(2) || '/',
            visitCount: item.visitCount || '0',
            registerTotal: item.registerTotal || '0',
            nextDayRetention: item.nextDayRetention || '/',
            sevenDayRetention: item.sevenDayRetention || '/',
            fifteenDayRetention: item.fifteenDayRetention || '/',
            thirtiethDayRetention: item.thirtiethDayRetention || '/',
          })
        })
        exportSheetTable({ fileName: fileName, tH_data: th_arr, tB_data: tb_arr, isSheet: true, merge: false })
      }
    })
    // } else {
    //   React.$message({
    //     type: 'error',
    //     content: "请选择日期"
    //   })
    // }
  }

  onChange(e) {
    this.setState({
      defaultActiveKey: e,
    }, () => {
      // if (e === '1') {
        // this.queryFormRef_devote.onReset()
      // } else {
        // this.queryFormRef_retained.onReset()
      // }
    })
  }

  render() {
    let { columns_devote, columns_retained, dataSource, defaultActiveKey, pageData, total, form_show, searchOption, overView } = this.state

    return (
      <div className="p-layout-box commodity-examine">
        <Tabs activeKey={defaultActiveKey} type="card" size={'small'} onChange={(e) => this.onChange(e)} >
          <TabPane key="1" tab="投放数据">
            <TheQueryForm ref={(ref) => this.queryFormRef_devote = ref} show={form_show} option={searchOption}
              onReset={() => this.onReset()}
              onGetValues={(values) => this.onFormSearch(values)} >
            </TheQueryForm>
            <TheButton size="middle" onClick={() => this.toExport(defaultActiveKey)} type="default">导出</TheButton>
            <div style={{ height: "120px", marginTop: '10px', marginBottom: "10px", display: "flex" }}>
              {/* <Row gutter={[16,8]} >
                <Col span={5} style={{ background: '#ececec' }}> */}
                  <div className='box'>
                    <div className='cardTitle'>激活用户</div>
                    <div className='cardMsg'>{overView.activeCount}</div>
                  </div>
                {/* </Col>
                <Col span={5} style={{ background: '#ececec' }}> */}
                  <div  className='box'>
                    <div className='cardTitle'>注册用户</div>
                    <div className='cardMsg'>{overView.registerCount}</div>
                  </div>
                {/* </Col>
                <Col span={5} style={{ background: '#ececec' }}> */}
                  <div  className='box'>
                    <div className='cardTitle'>付费用户</div>
                    <div className='cardMsg'>{overView.payCount}</div>
                  </div>
                {/* </Col>
                <Col span={5} style={{ background: '#ececec' }}> */}
                  <div  className='box'>
                    <div className='cardTitle'>付费金额</div>
                    <div className='cardMsg'><React.$price price={overView.registerPayPrice} /></div>
                  </div>
                {/* </Col>
              </Row> */}
            </div>
            <TheTable
              scroll={{ x: "max-content", y: '63vh' }}
              columns={columns_devote}
              dataSource={dataSource}
            />
            {
              dataSource.length > 0 &&
              <ThePagination
                pageNo={pageData.pageNo}
                pageSize={pageData.pageSize}
                total={total}
                pageChange={this.pageChange}
              />
            }
          </TabPane>
          <TabPane key="2" tab="留存效果">
            <TheQueryForm ref={(ref) => this.queryFormRef_retained = ref} show={form_show} option={searchOption}
              onReset={() => this.onReset()}
              onGetValues={(values) => this.onFormSearch(values)} >
            </TheQueryForm>
            <TheButton size="middle" onClick={() => this.toExport(defaultActiveKey)} type="default">导出</TheButton>
            <div style={{ width: '100%', height: "0px", marginTop: '10px', marginBottom: "10px" }}> </div>
            <TheTable
              scroll={{ x: "max-content", y: '63vh' }}
              columns={columns_retained}
              dataSource={dataSource}
            />
            {
              dataSource.length > 0 &&
              <ThePagination
                pageNo={pageData.pageNo}
                pageSize={pageData.pageSize}
                total={total}
                pageChange={this.pageChange}
              />
            }
          </TabPane>
        </Tabs>


      </div>
    );
  }
}
export default weChatAD
